package com.yukh.framework.crypto.hsm;

import com.yukh.framework.crypto.CryptoUtil;
import com.yukh.framework.crypto.HexUtil;

public class MacHsm {
	private static final int UNIT_LENGTH = 8;
	
	/**
	 * ECB: 
	 * @param mab
	 */
	public static String hsmECB(final byte[] mab){
		final byte [] mab_whole = CryptoUtil.appendTo8Multiple(mab);
		int unit_number = mab_whole.length/UNIT_LENGTH;
		byte [] xorResult = CryptoUtil.subByte(mab_whole, 0, 8);
		
		for (int i = 1; i < unit_number; i++) {
			int start = i * UNIT_LENGTH;
			int end = start + UNIT_LENGTH;
			byte[] unit = CryptoUtil.subByte(mab_whole, start, end);
			xorResult = CryptoUtil.doXor(xorResult, unit);
		}
		
		return HexUtil.encodeHexBinrary(xorResult);
	}
	
	/**
	 * 
	 * @param encTAK
	 * @return
	 */
	public static String getMsgToBeSend(String zakOnHSM, String mabStr) {
		StringBuffer msgRequest = new StringBuffer();
		msgRequest.append(HSMConst.MSG_HEAD);
		msgRequest.append("MA");
		msgRequest.append(zakOnHSM);
		msgRequest.append(mabStr);
		System.out.println("Racal message to be send: " + msgRequest.toString());
		return msgRequest.toString();
	}
}
